package com.bkgy.controller.qualityDaily.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bkgy.controller.qualityDaily.entity.QualitydailyQuestion;
import com.bkgy.controller.qualityDaily.entity.pdo.QuestionQueryReq;
import com.bkgy.controller.qualityDaily.entity.pdo.QuestionRepRes;
import com.bkgy.controller.qualityDaily.entity.pdo.QuestionSaveReq;
import com.bkgy.controller.qualityDaily.entity.pdo.QuestionSaveTable;
import com.bkgy.controller.qualityDaily.mapper.IQualitydailyQuestionMapper;
import com.bkgy.controller.qualityDaily.service.IQualitydailyQuestionService;
import com.bkgy.sys.common.entity.ResultData;
import com.bkgy.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class QualitydailyQuestionServiceImpl extends ServiceImpl<IQualitydailyQuestionMapper, QualitydailyQuestion> implements IQualitydailyQuestionService {

    @Override
    public ResultData questionRep(QuestionQueryReq req) {
        //没有开始、结束时间，默认查询当月
        LambdaQueryWrapper<QualitydailyQuestion> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(req.getArea()))
            wrapper.eq(QualitydailyQuestion::getArea, req.getArea());
        if (StringUtils.isNotEmpty(req.getDbegin())) {
            String shijian = req.getDbegin();
            wrapper.ge(QualitydailyQuestion::getYearMonthDay, shijian);
        } else {
            String shijian = DateUtil.thisMonthFirstDay("yyyy-MM-dd");
            wrapper.ge(QualitydailyQuestion::getYearMonthDay, shijian);
        }
        if (StringUtils.isNotEmpty(req.getDend())) {
            String shijian = req.getDend();
            wrapper.le(QualitydailyQuestion::getYearMonthDay, shijian);
        } else {
            String shijian = DateUtil.nextMonthFirstDay("yyyy-MM-dd");
            wrapper.le(QualitydailyQuestion::getYearMonthDay, shijian);
        }

        //初始化列表
        String[] unitArr = new String[]{"酸轧", "酸轧", "连退", "连退", "5#镀锌", "5#镀锌", "保障", "保障", "保障", "其它", "合计"};
        String[] belongArr = new String[]{"生产", "设备", "生产", "设备", "生产", "设备", "磨辊", "公辅", "运转", "", ""};
        List<QuestionRepRes> list = new ArrayList<>();
        for (int i = 0; i < unitArr.length; i++) {
            QuestionRepRes q = new QuestionRepRes();
            q.setUnit(unitArr[i]);
            q.setBelong(belongArr[i]);
            list.add(q);
        }

        QualitydailyQuestion question = null;

        //累计数据
        List<QualitydailyQuestion> dbList = list(wrapper);
        for (int index = 0; index < dbList.size(); index++) {
            QualitydailyQuestion q = dbList.get(index);
            if (q.getYearMonthDay().equals(DateUtil.getDateToString(new Date(), "yyyy-MM-dd"))) {
                question = q;
            }
            for (int i = 0; i < 10; i++) {
                QuestionRepRes row = list.get(i);
                try {
                    for (int j = 0; j <= 5; j++) {
                        BigDecimal v = (BigDecimal) q.getClass().getMethod("getCol" + i + j).invoke(q);
                        BigDecimal temp = (BigDecimal) row.getClass().getMethod("getCol" + j + j).invoke(row);
                        BigDecimal sumObj = temp.add(v);
                        row.getClass().getMethod("setCol" + j + j, BigDecimal.class).invoke(row, sumObj);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }

        //当日数据
        if (question == null) {
            LambdaQueryWrapper<QualitydailyQuestion> w = new LambdaQueryWrapper<>();
            w.eq(QualitydailyQuestion::getYearMonthDay, DateUtil.getDateToString(new Date(), "yyyy-MM-dd"));
            if (StringUtils.isNotEmpty(req.getArea()))
                w.eq(QualitydailyQuestion::getArea, req.getArea());
            question = getOne(w);
        }
        if (question != null) {
            for (int i = 0; i < 10; i++) {
                QuestionRepRes row = list.get(i);
                try {
                    for (int j = 0; j <= 5; j++) {
                        BigDecimal v = (BigDecimal) question.getClass().getMethod("getCol" + i + j).invoke(question);
                        row.getClass().getMethod("setCol" + j, BigDecimal.class).invoke(row, v);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }

        //合计行累加
        QuestionRepRes sumRow = list.get(list.size() - 1);
        for (int i = 0; i < list.size() - 1; i++) {
            QuestionRepRes q = list.get(i);
            sumRow.setCol0(sumRow.getCol0().add(q.getCol0()));
            sumRow.setCol00(sumRow.getCol00().add(q.getCol00()));
            sumRow.setCol1(sumRow.getCol1().add(q.getCol1()));
            sumRow.setCol11(sumRow.getCol11().add(q.getCol11()));
            sumRow.setCol2(sumRow.getCol2().add(q.getCol2()));
            sumRow.setCol22(sumRow.getCol22().add(q.getCol22()));
            sumRow.setCol3(sumRow.getCol3().add(q.getCol3()));
            sumRow.setCol33(sumRow.getCol33().add(q.getCol33()));
            sumRow.setCol4(sumRow.getCol4().add(q.getCol4()));
            sumRow.setCol44(sumRow.getCol44().add(q.getCol44()));
            sumRow.setCol5(sumRow.getCol5().add(q.getCol5()));
            sumRow.setCol55(sumRow.getCol55().add(q.getCol55()));
        }

        return ResultData.ResultDataSuccess(list, list.size());
    }

    @Override
    public ResultData<JSONObject> questionBarRep() {
        //当月数据
        LambdaQueryWrapper<QualitydailyQuestion> w = new LambdaQueryWrapper<>();
        w.ge(QualitydailyQuestion::getYearMonthDay, DateUtil.thisMonthFirstDay("yyyy-MM-dd"));
        w.orderByDesc(QualitydailyQuestion::getYearMonthDay);
        List<QualitydailyQuestion> list = list(w);
        QualitydailyQuestion question = new QualitydailyQuestion();
        if (list.size() == 0) {
            for (int i = 0; i < 10; i++) {
                for (int j = 0; j < 6; j++) {
                    try {
                        question.getClass().getMethod("setCol" + i + j, BigDecimal.class).invoke(question, BigDecimal.ZERO);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        //将当前月对象累计成一个对象
        for (QualitydailyQuestion que : list) {
            for (int i = 0; i < 10; i++) {
                for (int j = 0; j < 6; j++) {
                    try {
                        BigDecimal oldValue = (BigDecimal) question.getClass().getMethod("getCol" + i + j).invoke(question);
                        if (oldValue == null) oldValue = BigDecimal.ZERO;
                        BigDecimal newValue = (BigDecimal) que.getClass().getMethod("getCol" + i + j).invoke(que);
                        question.getClass().getMethod("setCol" + i + j, BigDecimal.class).invoke(question, oldValue.add(newValue));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        String[] seriesArr = new String[]{"酸轧", "连退", "5#镀锌", "其它"};
        JSONObject res = new JSONObject();
        JSONObject char1 = new JSONObject();
        char1.put("x", new String[]{"生产", "设备"});
        char1.put("series", seriesArr);
        char1.put("dataArr1", new BigDecimal[]{question.getCol00(), question.getCol20(), question.getCol40(),
                question.getCol60().add(question.getCol70()).add(question.getCol80()).add(question.getCol90())});
        char1.put("dataArr2", new BigDecimal[]{question.getCol10(), question.getCol30(), question.getCol50(),
                question.getCol60().add(question.getCol70()).add(question.getCol80()).add(question.getCol90())});
        res.put("char1", char1);
        JSONObject char2 = new JSONObject();
        char2.put("x", new String[]{"生产", "设备"});
        char2.put("series", seriesArr);
        char2.put("dataArr1", new BigDecimal[]{question.getCol01(), question.getCol21(), question.getCol41(),
                question.getCol61().add(question.getCol71()).add(question.getCol81()).add(question.getCol91())});
        char2.put("dataArr2", new BigDecimal[]{question.getCol11(), question.getCol31(), question.getCol51(),
                question.getCol61().add(question.getCol71()).add(question.getCol81()).add(question.getCol91())});
        res.put("char2", char2);
        JSONObject char3 = new JSONObject();
        char3.put("x", new String[]{"生产", "设备"});
        char3.put("series", seriesArr);
        char3.put("dataArr1", new BigDecimal[]{question.getCol02(), question.getCol22(), question.getCol42(),
                question.getCol62().add(question.getCol72()).add(question.getCol82()).add(question.getCol92())});
        char3.put("dataArr2", new BigDecimal[]{question.getCol12(), question.getCol32(), question.getCol52(),
                question.getCol62().add(question.getCol72()).add(question.getCol82()).add(question.getCol92())});
        res.put("char3", char3);
        return ResultData.ResultDataSuccess(res);
    }

    @Override
    public ResultData<String> saveQualitydailyQuestion(QualitydailyQuestion obj) {
        boolean res = false;
        res = save(obj);
        return ResultData.ResultDataSuccess(res ? "SUCCESS" : "FAIL");
    }

    @Override
    public ResultData<String> updateQualitydailyQuestion(QualitydailyQuestion obj) {
        boolean res = false;
        res = updateById(obj);
        return ResultData.ResultDataSuccess(res ? "SUCCESS" : "FAIL");
    }

    @Override
    public ResultData<String> deleteQualitydailyQuestion(QualitydailyQuestion obj) {
        boolean res = false;
        if (obj.getId() != null)
            res = removeById(obj.getId());
        else {
            LambdaQueryWrapper<QualitydailyQuestion> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(QualitydailyQuestion::getYearMonthDay, obj.getYearMonthDay()).eq(QualitydailyQuestion::getArea, obj.getArea());
            remove(wrapper);
        }
        return ResultData.ResultDataSuccess(res ? "SUCCESS" : "FAIL");
    }

    @Override
    public ResultData selectPage(QuestionQueryReq req) {
        Page<QualitydailyQuestion> p = new Page<>(req.getPageIndex(), req.getPageSize());
        LambdaQueryWrapper<QualitydailyQuestion> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(req.getDbegin())) {
            String shijian = req.getDbegin();
            wrapper.ge(QualitydailyQuestion::getYearMonthDay, shijian);
        }
        if (StringUtils.isNotEmpty(req.getDend())) {
            String shijian = req.getDend();
            wrapper.le(QualitydailyQuestion::getYearMonthDay, shijian);
        }
        if (StringUtils.isNotEmpty(req.getArea())) wrapper.eq(QualitydailyQuestion::getArea, req.getArea());
        List<QualitydailyQuestion> dbList = page(p, wrapper).getRecords();
        List<QuestionSaveReq> list = new ArrayList<>();
        String[] unitArr = new String[]{"酸轧", "酸轧", "连退", "连退", "5#镀锌", "5#镀锌", "保障", "保障", "保障", "其它"};
        String[] belongArr = new String[]{"生产", "设备", "生产", "设备", "生产", "设备", "磨辊", "公辅", "运转", "其它",};
        for (QualitydailyQuestion qm : dbList) {
            QuestionSaveReq obj = new QuestionSaveReq();
            obj.setId(qm.getId());
            obj.setYearMonthDay(qm.getYearMonthDay());
            obj.setArea(qm.getArea());
            obj.setCreateTime(qm.getCreateTime());

            List<QuestionSaveTable> tableList = new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                try {
                    QuestionSaveTable table = new QuestionSaveTable();
                    table.setArea(qm.getArea());
                    table.setUnit(unitArr[i]);
                    table.setBelong(belongArr[i]);
                    table.setOne((BigDecimal) qm.getClass().getMethod("getCol" + i + 0).invoke(qm));
                    table.setTwo((BigDecimal) qm.getClass().getMethod("getCol" + i + 1).invoke(qm));
                    table.setThree((BigDecimal) qm.getClass().getMethod("getCol" + i + 2).invoke(qm));
                    table.setCompanyone((BigDecimal) qm.getClass().getMethod("getCol" + i + 3).invoke(qm));
                    table.setCompanytwo((BigDecimal) qm.getClass().getMethod("getCol" + i + 4).invoke(qm));
                    table.setCompanythree((BigDecimal) qm.getClass().getMethod("getCol" + i + 5).invoke(qm));
                    tableList.add(table);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            obj.setQuestionTable(tableList);
            list.add(obj);
        }
        return ResultData.ResultDataSuccess(list, list.size());
    }
}
